/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 聚单客服务商管理
 */

import React, { useRef, useState, useEffect } from 'react';
import { Button, message, Space } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbEditLeague from '@/components/_pages/jdk/addLeague/compinents/KbEditLeague/';
import KbRemarksModal from '@/components/KbRemarksModal';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { LEAGUE_COLUMNS } from '@/components/_pages/jdk/index.d';
import KeepAlive from '@base/components/keep-alive';
import { usePaginationCache } from '@base/components/keep-alive/_utils';
import { getLeagueList } from '@/services/jdk/league';
import { leagueColumns } from '@/components/_pages/jdk/index.config';
import { saveLeague } from '@/services/jdk/league';
import { usePageTabsChange } from '@/utils/hooks/pageTabs';
import { useSelector, history } from 'umi';
import styles from './index.less';

const Index = () => {
  const actionRef = useRef<ActionType>();
  const [show] = usePageTabsChange();
  const [record, setRecord] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const proFormRef = useRef<ProFormInstance>();
  const formDataRef = useRef<any>(null);
  const [remarkItem, setRemarkItem] = useState<any>({});
  const [remarkVisible, setRemarkVisible] = useState<boolean>(false);

  const onClose = () => {
    setVisible(false);
    setRecord({});
  };
  const handelAddLeague = () => setVisible(true);
  const handleOption = (record_: any) => {
    const { agent_area_code: agent_area } = record_;
    setRecord({ agent_area, ...record_ });
    handelAddLeague();
  };

  const handleRemark = (record_: any) => {
    setRemarkItem(record_);
    setRemarkVisible(true);
  };

  const handleDetail = (record_: any) => {
    const { league_id } = record_;
    history.push({
      pathname: '/f/jdk/league/details',
      query: { league_id },
    });
  };

  const pagination = usePaginationCache('table', {
    pageSize: 20,
    showQuickJumper: false,
    showSizeChanger: false,
  });

  const recordFormData = (param: any) => {
    const { search } = param as any;
    formDataRef.current = {
      search,
    };
    proFormRef.current?.setFieldsValue(formDataRef.current);
  };

  const onSubmit = async (values: any) => {
    if (record && record.league_id) {
      values.league_id = record?.league_id;
    }
    const { address, agent_area } = values;
    values.address = JSON.stringify(address);
    values.agent_area = JSON.stringify(agent_area);

    saveLeague(values).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        actionRef.current?.reload();
        message.success(msg);
        onClose();
      } else {
        message.error(msg);
      }
    });
  };

  const optionColumns: ProColumns<LEAGUE_COLUMNS>[] = [
    {
      title: '操作',
      valueType: 'option',
      width: winSize === 'xs' ? 80 : 120,
      align: 'center',
      fixed: 'right',
      render: (_, item) => {
        return (
          <Space direction='vertical'>
            <a onClick={handleOption.bind(null, item)}>修改</a>
            <a onClick={handleDetail.bind(null, item)}>详情</a>
            <a onClick={handleRemark.bind(null, item)}>备注</a>
          </Space>
        );
      },
    },
  ];
  const queryTable = async (values: any) => {
    const { current: page, pageSize } = values;
    if (!formDataRef.current) {
      recordFormData(proFormRef.current?.getFieldsValue());
    }
    const { code, data, msg } = await getLeagueList({ page, pageSize, ...formDataRef.current });
    const list = data.list.map((item: any, index: number) => ({
      ...item,
      id: index + 1,
    }));
    if (code == 0) {
      return {
        data: list,
        total: data.total,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  const onProFormSubmit = async (values: any) => {
    recordFormData(values);
    actionRef.current?.reload(true);
  };
  useEffect(() => {
    if (show) actionRef.current?.reload(false);
  }, [show]);
  return (
    <PageContainer className={styles.main}>
      <DragTable>
        <ProTable
          rowKey='league_id'
          cardProps={{
            title: [
              <KeepAlive cacheId='form' key='form'>
                <ProForm
                  formRef={proFormRef}
                  layout='inline'
                  onFinish={onProFormSubmit}
                  initialValues={{
                    department: '1',
                    type: 'name',
                  }}
                  submitter={{
                    searchConfig: {
                      submitText: '查询',
                    },
                    onReset: () => {
                      recordFormData({});
                      actionRef.current?.reload(true);
                    },
                  }}
                >
                  <ProFormText
                    fieldProps={{
                      style: { width: '220px' },
                    }}
                    name='search'
                    placeholder='输入服务商名称/账号查询'
                  />
                </ProForm>
              </KeepAlive>,
            ],
            extra: [
              <Button key='add' type='primary' onClick={handelAddLeague}>
                添加服务商
              </Button>,
            ],
          }}
          actionRef={actionRef}
          request={queryTable}
          columns={[...leagueColumns, ...optionColumns]}
          toolBarRender={false}
          pagination={pagination}
          search={false}
          scroll={{
            x: 1200,
          }}
        />
        <KbEditLeague visible={visible} onSubmit={onSubmit} record={record} onClose={onClose} />
      </DragTable>
      <KbRemarksModal
        modalTitle={`添加备注 ｜ ${remarkItem.league_name} - ${remarkItem.phone}`}
        required
        visible={remarkVisible}
        setVisible={setRemarkVisible}
        formatDataMap={{
          label: 'operate_name',
          remark: 'remark',
          user: 'operate_phone',
          time: 'create_time',
        }}
        api='/jdk/League/leagueRemark'
        formData={{ user_id: remarkItem.league_id }}
        listApi='/jdk/League/getLeagueRemarkList'
        listFormData={{ user_id: remarkItem.league_id }}
      />
    </PageContainer>
  );
};

export default Index;
